package com.yanchangapp.ui.activity.msg;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.yanchangapp.commom.LoadingType;
import com.zxl.baselib.ui.base.BaseActivity;
import com.zxl.baselib.util.ui.UIUtils;
import com.yanchangapp.R;
import com.yanchangapp.adapter.part.MsgContentAdapter;
import com.yanchangapp.commom.AppConstant;
import com.yanchangapp.model.bean.MsgContentBean;
import com.yanchangapp.model.bean.MsgTypeBean;
import com.yanchangapp.ui.presenter.MsgCntAtPresenter;
import com.yanchangapp.ui.view.MsgCntAtView;
import com.yanchangapp.widget.MsgPopupWindow;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * 编辑状态下不能够切换即可...
 * <p>
 * 编辑状态不可刷新和加载...
 *
 * 上拉加载更多注意条目数量
 */
public class MessageActivity extends BaseActivity<MsgCntAtView, MsgCntAtPresenter> implements MsgCntAtView, MsgContentAdapter.MsgCntListener {
    @BindView(R.id.ivToolbarNavigation)
    ImageView ivToolbarNavigation;
    @BindView(R.id.vToolbarDivision)
    View vToolbarDivision;
    @BindView(R.id.tvToolbarTitle)
    TextView tvToolbarTitle;
    @BindView(R.id.tv_publish_now)
    TextView tvPublishNow;
    @BindView(R.id.tvMessageDes)
    TextView tvMessageDes;
    @BindView(R.id.ivArrow)
    ImageView ivArrow;
    @BindView(R.id.llMsgTitle)
    LinearLayout llMsgTitle;
    @BindView(R.id.recycleMsgList)
    RecyclerView mRecyclerList;
    @BindView(R.id.llSetRead)
    LinearLayout mLlSetRead;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.btnNextRefresh)
    TextView btnNextRefresh;
    @BindView(R.id.llErrorNetwork)
    LinearLayout llErrorNetwork;
    @BindView(R.id.llEmptyMsg)
    LinearLayout llEmptyMsg;

    private List<MsgTypeBean> mMsgTypeBeanList;
    private List<MsgContentBean> mMsgContentBeanList = new ArrayList<>();
    private MsgPopupWindow mMsgPopupWindow;
    private Integer currentType = null;
    private boolean isEditor = false;
    private MsgContentAdapter mMsgContentAdapter;
    private int currentPage = AppConstant.FIRST_PAGE_NUM;

    public static void show(Activity context) {
        context.startActivity(new Intent(context, MessageActivity.class));
        context.overridePendingTransition(R.anim.screen_zoom_in, R.anim.screen_zoom_out);
    }

    private static final String TAG = "消息";
    private List<Integer> mSelectList = new ArrayList<>();

    @Override
    protected void init() {
        // 初始化MSG类型...
        mMsgTypeBeanList = new ArrayList<>();
        mMsgTypeBeanList.add(new MsgTypeBean(null, "全部消息", true));
        mMsgTypeBeanList.add(new MsgTypeBean(2, "计划类", false));
        mMsgTypeBeanList.add(new MsgTypeBean(1, "审批类", false));
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_message;
    }

    @Override
    protected MsgCntAtPresenter createPresenter() {
        return new MsgCntAtPresenter(this);
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        refreshLayout.setEnableRefresh(true);
        refreshLayout.setEnableLoadMore(true);
        initTitle();
        setMsgPopupWindow();
        initMsgAdapter();
    }

    private void setLoadingState(LoadingType loadingType){
        switch (loadingType){
            case SUCCESS:
                if (llEmptyMsg.getVisibility() == View.VISIBLE){
                    llEmptyMsg.setVisibility(View.GONE);
                }

                if (llErrorNetwork.getVisibility() == View.VISIBLE){
                    llErrorNetwork.setVisibility(View.GONE);
                }

                // 设置布局隐藏
                if (refreshLayout.getVisibility() == View.GONE){
                    refreshLayout.setVisibility(View.VISIBLE);
                }
                break;
            case ERROR:
                if (llEmptyMsg.getVisibility() == View.VISIBLE){
                    llEmptyMsg.setVisibility(View.GONE);
                }

                if (llErrorNetwork.getVisibility() == View.GONE){
                    llErrorNetwork.setVisibility(View.VISIBLE);
                }

                // 设置布局隐藏
                if (refreshLayout.getVisibility() == View.VISIBLE){
                    refreshLayout.setVisibility(View.GONE);
                }
                break;
            case EMPTY:
                if (llEmptyMsg.getVisibility() == View.GONE){
                    llEmptyMsg.setVisibility(View.VISIBLE);
                }

                if (llErrorNetwork.getVisibility() == View.VISIBLE){
                    llErrorNetwork.setVisibility(View.GONE);
                }

                // 设置布局隐藏
                if (refreshLayout.getVisibility() == View.VISIBLE){
                    refreshLayout.setVisibility(View.GONE);
                }
                break;
        }
    }

    private void initTitle() {
        setMsgTitle();
        tvPublishNow.setVisibility(View.VISIBLE);
        setEditText();
    }

    private void setMsgTitle() {
        tvToolbarTitle.setText(getString(R.string.message_title, String.valueOf(mMsgContentBeanList.size())));
    }

    private void setEditText() {
        tvPublishNow.setText(isEditor ? "取消" : "编辑");
    }

    private void setMsgPopupWindow() {
        mMsgPopupWindow = new MsgPopupWindow(this, mMsgTypeBeanList);
        mMsgPopupWindow.setImageView(ivArrow);
        llMsgTitle.setOnClickListener(v -> {
            // 如果编辑状态 则不能切换...
            if (isEditor) {
                return;
            }

            if (mMsgPopupWindow.isShowing()) {
                mMsgPopupWindow.dismiss();
            } else {
                mMsgPopupWindow.showAsDropDown(llMsgTitle);
            }
        });

        // 进行切换....
        mMsgPopupWindow.setOnItemSelectedListener(bean -> {
            mMsgPopupWindow.dismiss();
            tvMessageDes.setText(bean.getMsgDescription());
            // 当前类型
            currentType = bean.getMsgType();
            refreshLayout.resetNoMoreData();
            doRefresh();
        });
    }

    private void resetState(){
        mRecyclerList.setVisibility(View.VISIBLE);
        llEmptyMsg.setVisibility(View.GONE);
        llErrorNetwork.setVisibility(View.GONE);
    }

    // 有内容的情况
    private void hasContentState(){
        if (mRecyclerList.getVisibility() == View.GONE){
            mRecyclerList.setVisibility(View.VISIBLE);
            llEmptyMsg.setVisibility(View.GONE);
            llErrorNetwork.setVisibility(View.GONE);
        }
    }

    // 错误情况
    private void errState(){
        if (llErrorNetwork.getVisibility() == View.GONE){
            mRecyclerList.setVisibility(View.GONE);
            llEmptyMsg.setVisibility(View.GONE);
            llErrorNetwork.setVisibility(View.VISIBLE);
        }
    }

    // 空界面
    private void emptyState(){
        if (llEmptyMsg.getVisibility() == View.GONE){
            mRecyclerList.setVisibility(View.GONE);
            llEmptyMsg.setVisibility(View.VISIBLE);
            llErrorNetwork.setVisibility(View.GONE);
        }
    }


    private void initMsgAdapter() {
        mRecyclerList.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        mRecyclerList.addItemDecoration(new DividerItemDecoration(this,DividerItemDecoration.VERTICAL));
        mMsgContentAdapter = new MsgContentAdapter(this, mMsgContentBeanList, this);
        mRecyclerList.setAdapter(mMsgContentAdapter);
    }


    @Override
    protected void initData() {
        // 进行初始化.....
        currentPage = AppConstant.FIRST_PAGE_NUM;
        mPresenter.refreshMsgList(currentType);
    }

    @Override
    protected void initListener() {
        tvPublishNow.setOnClickListener(v -> {
            if (!isEditor && mMsgContentBeanList.size() == 0){
                return;
            }

            isEditor = !isEditor;
            tvMessageDes.setSelected(isEditor);
            ivArrow.setSelected(isEditor);
            setEditText();
            if (isEditor) {
                setListCannotRefresh();
            } else {
                setListCanRefresh();
            }
            // 清除已选中的cb
            mSelectList.clear();
            if (mLlSetRead.getVisibility() == View.VISIBLE){
                mLlSetRead.setVisibility(View.GONE);
            }
            // 进行切换...
            mMsgContentAdapter.setEditState(isEditor);
            mMsgContentAdapter.notifyDataSetChanged();
        });

        ivToolbarNavigation.setOnClickListener(v -> {
            if (isEditor){
                tvPublishNow.performClick();
            }else {
                finish();
                overridePendingTransition(R.anim.screen_zoom_in, R.anim.screen_zoom_out);
            }
        });

        // 设置为已读
        mLlSetRead.setOnClickListener(v -> {
            setListCanRefresh();
            mPresenter.setMsgReadedState(mSelectList);
        });

        refreshLayout.setOnRefreshListener(refreshLayout ->
                doRefresh());

        refreshLayout.setOnLoadMoreListener(refreshLayout ->
                mPresenter.loadMoreMsgList(currentType, currentPage));

        btnNextRefresh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                doRefresh();
            }
        });
    }


    private void doRefresh() {
        setListCanRefresh();
        currentPage = AppConstant.FIRST_PAGE_NUM;
        mPresenter.refreshMsgList(currentType);
    }

    private void setListCanRefresh() {
        refreshLayout.setEnableRefresh(true);
        refreshLayout.setEnableLoadMore(true);
    }

    private void setListCannotRefresh() {
        refreshLayout.setEnableRefresh(false);
        refreshLayout.setEnableLoadMore(false);
    }

    @Override
    public void refreshMsgSuccess(List<MsgContentBean> msgContentBeanList) {
        refreshLayout.finishRefresh();
        if (msgContentBeanList != null && msgContentBeanList.size() != 0) {
            mMsgContentBeanList.clear();
            mMsgContentBeanList.addAll(msgContentBeanList);
            setLoadingState(LoadingType.SUCCESS);
        } else {
            mMsgContentBeanList.clear();
            setLoadingState(LoadingType.EMPTY);
        }
        mMsgContentAdapter.setEditState(false);
        mMsgContentAdapter.notifyDataSetChanged();
        // 设置标题....
        setMsgTitle();
    }

    @Override
    public void refreshMsgFailure(String msg) {
        UIUtils.showToast(msg);
        if (refreshLayout != null) {
            refreshLayout.finishRefresh();
            refreshLayout.resetNoMoreData();
        }
        if (mMsgContentBeanList.size() == 0){
            errState();
        }else {
            setListCannotRefresh();
        }
    }


    @Override
    public void loadMoreMsgFailure(String msg) {
        UIUtils.showToast(msg);
        currentPage--;
    }

    @Override
    public void loadMoreMsgSuccess(List<MsgContentBean> msgContentBeanList) {
        if (null == msgContentBeanList || msgContentBeanList.size() == 0) {
            // 说明是无数据了
            currentPage--;
            refreshLayout.finishLoadMoreWithNoMoreData();
        } else {
            this.mMsgContentBeanList.addAll(msgContentBeanList);
            mMsgContentAdapter.notifyDataSetChanged();
            setMsgTitle();
            refreshLayout.finishLoadMore();
        }
    }

    @Override
    public void setReadedSuccess() {
        isEditor = false;
        setEditText();
        ivArrow.setSelected(false);
        tvMessageDes.setSelected(false);
        // 进行数据刷新
        mPresenter.refreshMsgList(currentType);
        // 设置不可见
        mLlSetRead.setVisibility(View.GONE);

    }

    @Override
    public void setReadedFailure(String msg) {
        UIUtils.showToast(msg);
    }


    // 条目点击事件...
    @Override
    public void onItemClickListener(int position, MsgContentBean msgContentBean) {
        // todo 编辑状态下的点击事件...
    }

    @Override
    public void onCheckChangedListener(int position, boolean state) {
        if (position > mMsgContentBeanList.size() - 1) {
            return;
        }
        int currentID = mMsgContentBeanList.get(position).getId();
        if (state) {
            // 进行添加...
            mSelectList.add(currentID);
        } else {
            int index = mSelectList.indexOf(currentID);
            if (index != -1) {
                mSelectList.remove(index);
            }
        }
        Log.e(TAG, mSelectList.toString());
        if (mSelectList.size() == 0) {
            mLlSetRead.setVisibility(View.GONE);
        } else {
            mLlSetRead.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK){
            if (isEditor){
                tvPublishNow.performClick();
                return  false;
            }else {
                finish();
                overridePendingTransition(R.anim.screen_zoom_in, R.anim.screen_zoom_out);
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }
}
